package com.ebelter.myehc.ui.fragments.modifys;


import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ebelter.btcomlib.CommonLib;
import com.ebelter.btcomlib.bases.fragment.BaseFragment;
import com.ebelter.btcomlib.common.Constants;
import com.ebelter.btcomlib.models.beans.ScaleUser;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.AppUtils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.activity_manager.ActivityManagers;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.WeightSelectDialog;
import com.ebelter.btcomlib.views.WheelView;
import com.ebelter.btcomlib.views.dialogs.TextTipDialog;
import com.ebelter.btcomlib.views.dialogs.WheelViewDialog;
import com.ebelter.btcomlib.views.dialogs.picktime2.CustomDatePicker;
import com.ebelter.myehc.R;
import com.ebelter.myehc.models.http.request.EhcNetUtils;
import com.ebelter.myehc.models.http.response.RegisterBT;
import com.ebelter.myehc.ui.activitys.LoginActivity;
import com.ebelter.myehc.ui.activitys.MainActivity;
import com.ebelter.myehc.ui.activitys.ModifyInfoActivity;
import com.ebelter.myehc.ui.activitys.TrendActivity;
import com.ebelter.myehc.ui.view.CombinView4;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.ebelter.btcomlib.views.dialogs.TextTipDialog.Gravity_BUTTOM;
import static com.ebelter.myehc.ui.activitys.LoginActivity.getAgeByBirthday;
import static com.ebelter.myehc.ui.activitys.LoginActivity.getBirthdayIntValue;


/**
 * 血糖
 */
public class ModifyAddInfo_Fragment extends BaseFragment implements View.OnClickListener {


    public static final String TAG = "ModifyAddInfo_Fragment";
    private TextView m_title_tv;
    private TextView m_righttitle_tv;
    private ImageView top_left_iv;



    private CombinView4 sex_man;
    private CombinView4 sex_woman;

    private TextView addinfo_gender_title_tv;
    private TextView addinfo_birthday_title_tv;
    private TextView addinfo_height_title_tv;

    private TextView addinfo_birthday_tv;
    private TextView height_tv;
    private TextView addinfo_weight_tv;

    private TextView complete_tv;

    private int currentSelectSex;//0男1女
    private int currentHeight = 170;//身高
    private String currentBirthday;//生日



    @Override
    protected int setLayoutResouceId() {
        return R.layout.fragment_modify_addinfo;
    }

    @Override
    protected void initView() {
        super.initView();
        FV();
        m_title_tv.setText(R.string.qtxzl);
        ViewUtils.hideView(m_righttitle_tv);





    }
    @Override
    protected void setListener() {
        super.setListener();

       // m_righttitle_tv.setOnClickListener(this);
        top_left_iv.setOnClickListener(this);
        sex_man.setOnClickListener(this);
        sex_woman.setOnClickListener(this);

        addinfo_birthday_tv.setOnClickListener(this);

        height_tv.setOnClickListener(this);
        addinfo_weight_tv.setOnClickListener(this);
        complete_tv.setOnClickListener(this);


    }

    @Override
    protected void initData(Bundle arguments) {
        super.initData(arguments);


//        UserSpUtil.writeString(Constants.IUser.ehc_token,ehcLoginBt.result.token);
//        UserSpUtil.writeString(Constants.IUser.ehc_email,ehcLoginBt.result.email);
//        UserSpUtil.writeString(Constants.IUser.ehc_name,ehcLoginBt.result.name);
//        UserSpUtil.writeInt(Constants.IUser.ehc_age,ehcLoginBt.result.age);
//        UserSpUtil.writeInt(Constants.IUser.ehc_id,ehcLoginBt.result.id);
//        UserSpUtil.writeString(Constants.IUser.ehc_sex,ehcLoginBt.result.sex);
//        UserSpUtil.writeInt(Constants.IUser.ehc_phone_no,ehcLoginBt.result.phone_no);
//        UserSpUtil.writeInt(Constants.IUser.ehc_phone_region,ehcLoginBt.result.phone_region);

        if ("M".equals(UserSpUtil.readString(Constants.IUser.ehc_sex))){
            currentSelectSex=0;
        }else {
            currentSelectSex=1;
        }


        setSex(currentSelectSex);
    }

    private void FV() {
        m_title_tv=mRootView.findViewById(R.id.m_title_tv);
        m_righttitle_tv=mRootView.findViewById(R.id.m_righttitle_tv);
        top_left_iv=mRootView.findViewById(R.id.top_left_iv);
        addinfo_gender_title_tv=mRootView.findViewById(R.id.addinfo_gender_title_tv);
        addinfo_birthday_title_tv=mRootView.findViewById(R.id.addinfo_birthday_title_tv);
        addinfo_height_title_tv=mRootView.findViewById(R.id.addinfo_height_title_tv);

        sex_man=mRootView.findViewById(R.id.cb4_man);
        sex_woman=mRootView.findViewById(R.id.cb4_women);

        if (TextUtils.equals(AppUtils.en, AppUtils.getLocalStr())){
            sex_man.setSize(10);
            sex_woman.setSize(10);
            ViewUtils.setWeight(sex_man,1.5f);
            ViewUtils.setWeight(sex_woman,1.5f);

            ViewUtils.setTextSize(addinfo_gender_title_tv,12);
            ViewUtils.setTextSize(addinfo_birthday_title_tv,12);
            ViewUtils.setTextSize(addinfo_height_title_tv,12);
            ViewUtils.setWeight(addinfo_birthday_title_tv,1.5f);
        }


        addinfo_birthday_tv=mRootView.findViewById(R.id.addinfo_birthday_tv);

        height_tv=mRootView.findViewById(R.id.addinfo_height_tv);
        addinfo_weight_tv=mRootView.findViewById(R.id.addinfo_weight_tv);
        complete_tv=mRootView.findViewById(R.id.comple_tv);

        m_righttitle_tv.setText(R.string.done);


    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_left_iv:
                back();
                break;
            case R.id.cb4_man:
                setSex(0);
                    break;
            case R.id.cb4_women:
                setSex(1);
                    break;
            case R.id.addinfo_birthday_tv:
                showBirthday();
                break;
            case R.id.addinfo_height_tv:
                showHeight();
                break;
            case R.id.addinfo_weight_tv:
                showWeight();
                break;
            case R.id.comple_tv:
                complete();
                break;

        }
    }
    private float weightValue;
    private float weightValue2;
    private void showWeight() {
        WeightSelectDialog weightSelectDialog=new WeightSelectDialog(getActivity());
        weightSelectDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                setTextImage(addinfo_weight_tv,R.drawable.ic_xiala);
            }
        });
        weightValue =UserSpUtil.readFloat(Constants.IUser.WEIGHT,50);
        weightValue2=weightValue;
        weightSelectDialog.show(weightValue);
        weightSelectDialog.setValueChange(new WeightSelectDialog.ValueChange() {
            @Override
            public void change(float value) {
                LogUtils.i(TAG,"--weightSelectDialog--setValueChange--value = "+value);
                weightValue2 = value;
            }
        });

        weightSelectDialog.setBackgroundColor(getResources().getColor(R.color.redTheme));
        weightSelectDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {}//内部已经处理了

            @Override
            public void ok(Dialog dialogView) {
                weightValue=weightValue2;
                if (addinfo_weight_tv!=null){addinfo_weight_tv.setText(weightValue+" Kg");}

            }
        });
    }

    private void showBirthday() {
        setTextImage(addinfo_birthday_tv,R.drawable.ic_shangla);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String time = sdf.format(new Date());
        String date = time.split(" ")[0];
        CustomDatePicker datePicker= new CustomDatePicker(getContext(),new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                LogUtils.i(TAG,time);
                currentBirthday=time;
                ViewUtils.setTextViewStr(addinfo_birthday_tv,TrendActivity.getDisTime(0,TimeUtils.parseFormatter6Time(currentBirthday).getTime()));


            }
        }, "1945-01-01 00:00", time);
        // datePicker.setSelectedCalender("1991-06-13");
        datePicker.showSpecificTime(false); //显示时和分
        datePicker.setIsLoop(false);
        datePicker.setDayIsLoop(true);
        datePicker.setMonIsLoop(true);
        datePicker.show(date);
        datePicker.setSelectedTime(currentBirthday);
        datePicker.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (addinfo_birthday_tv!=null){
                    setTextImage(addinfo_birthday_tv,R.drawable.ic_xiala);
                }
            }
        });
        datePicker.setBackgroundColor(getResources().getColor(R.color.redTheme));



    }

    private void showHeight() {


        if (getContext()==null) return;

        setTextImage(height_tv,R.drawable.ic_shangla);


        WheelViewDialog wheelViewDialog = new WheelViewDialog(getContext());
        wheelViewDialog.setGravity(Gravity_BUTTOM);


        List<String> list=new ArrayList<>();
        for (int i=100;i<230;i++){
            list.add(i+" CM");
        }
        wheelViewDialog.setOffeset(1);
        wheelViewDialog.setItems(list);
        wheelViewDialog.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                Log.i(TAG, "selectedIndex: " + selectedIndex + ", item: " + item);
                currentHeight = NumUtils.string2Int(item.replace(" CM",""));
            }
        });


        wheelViewDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView) {
                dialogView.cancel();

                if (height_tv!=null)height_tv.setText(currentHeight+" CM");
            }
        });

        wheelViewDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                setTextImage(height_tv,R.drawable.ic_xiala);
            }
        });
        wheelViewDialog.setSelectPosition(currentHeight-100);
        wheelViewDialog.show();

    }



    private List<String> getListString(int from,int to,String unit){

        List<String> list=new ArrayList<>();
        for (int i=from;i<to;i++){
            list.add(i+unit);
        }
        return list;
    }

    public static void setTextImage(TextView textView, int res) {
        if (textView==null){
            return;
        }
        Drawable drawable = CommonLib.APPContext.getResources().getDrawable(res);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable, null);
    }



    private void back() {
        if (mActivity!=null)mActivity.finish();
    }

    public void complete() {
        if (TextUtils.isEmpty(currentBirthday)){
            ToastUtil.show(R.string.qxzchshny);
            return;
        }

        if (currentHeight==0){
            ToastUtil.show(R.string.qxzshg);
            return;
        }

        LogUtils.i(TAG,"性别："+currentSelectSex+"---生日:"+currentBirthday.substring(0,10)+"---身高："+currentHeight);



       // final String name= UserSpUtil.readString(Constants.IUser.p_username);
       // final String name= UserSpUtil.readString(Constants.IUser.ehc_name);
        final String ehc_phone_no = UserSpUtil.readInt(Constants.IUser.ehc_phone_no)+"";
        final String ehc_email= UserSpUtil.readString(Constants.IUser.ehc_email);
        final String sex = (currentSelectSex+1)+"";//因为服务器那边的是1男2女
        final String birthday = currentBirthday.substring(0,10);
        String height = currentHeight+"";
        final String weight = weightValue+"";
        String dtype = "400";
        String softver = AppUtils.getVerName(getContext());
        int userId =  UserSpUtil.readInt(Constants.IUser.ehc_id,-1);
        if (userId==-1){
            throw new RuntimeException("p_id==-1 运行时异常");
        }

        String userId2=userId+"";
        String sn="EHC";
        String pwd= UserSpUtil.readString(Constants.IUser.ehc_p);

        EhcNetUtils.getInstance().registerUserBT(this, ehc_phone_no, ehc_email, sex, birthday,
                height, weight, dtype, softver, userId2, sn, pwd, new HttpResponse<RegisterBT>() {
                    @Override
                    public void result(boolean isRequestSuccess, String requestDes, RegisterBT registerBT, String s) {
                        LogUtils.i(TAG,"注册 s = " + s);
                        if (isRequestSuccess && registerBT.resultCode == 1){
                            LogUtils.i(TAG,"注册成功");

                            saveUserData(ehc_phone_no,ehc_email,sex,birthday,Float.parseFloat(weight),registerBT.resultMessage.authkey);

                            Intent intent=new Intent(getContext(), MainActivity.class);
                            startActivity(intent);

                            ActivityManagers.getInstance().closeActivity(LoginActivity.TAG);//关闭界面的意思
                            ActivityManagers.getInstance().closeActivity(ModifyInfoActivity.TAG);

                        }else {
                            LogUtils.i(TAG,"注册失败");
                        }
                    }
                });


    }


    private void saveUserData(String name, String userName, String sex, String birthday,float weight,String authkey) {
        //保存登录用户数据

      //  String userid = "000f0001000001";
        long userid2=10000000000000L+UserSpUtil.readInt(Constants.IUser.ehc_id,0);
        UserSpUtil.writeString(Constants.IUser.USER_ID,userid2+"");

        String btId = ScaleUser.toBtId(userid2+"");
        UserSpUtil.writeString(Constants.IUser.BT_ID,btId);

        UserSpUtil.writeInt(Constants.IUser.HEIGHT,currentHeight);
        UserSpUtil.writeFloat(Constants.IUser.WEIGHT,weight);

        UserSpUtil.writeString(Constants.IUser.BIRTHDAY,birthday);

        int year = getBirthdayIntValue(birthday,0,1990);
        UserSpUtil.writeInt(Constants.IUser.YEAR,year);
        UserSpUtil.writeInt(Constants.IUser.MONTHS,getBirthdayIntValue(birthday,1,6));
        UserSpUtil.writeInt(Constants.IUser.DAY,getBirthdayIntValue(birthday,2,1));
        UserSpUtil.writeInt(Constants.IUser.AGE,getAgeByBirthday(year));


        UserSpUtil.writeInt(Constants.IUser.SEX,currentSelectSex);//0男1女
        UserSpUtil.writeInt(Constants.IUser.PROFESSION,0); //0普通人1运动员
        UserSpUtil.writeFloat(Constants.IUser.IMPEDANCE,500);
        UserSpUtil.writeBoolean(Constants.IUser.IS_KG_MODEL,true);

        UserSpUtil.writeString(Constants.IUser.AUTH_KEY,authkey);



    }


    public void setSex(int sex) {
        this.currentSelectSex=sex;
        if (sex_man!=null) sex_man.setImage(0);
        if (sex_woman!=null) sex_woman.setImage(0);
        if (sex==0){
            if (sex_man!=null) sex_man.setImage(R.drawable.ic_guo);
        }else {
            if (sex_woman!=null) sex_woman.setImage(R.drawable.ic_guo);
        }
    }
}
